var template = `
<div class="heartbeat">
</div>
`;

let HeartBeat = {
    name: 'HeartBeat',
    components: {},
    template,
    props: {
        list: {
            type: Array,
            default: []
        },
        heartBeat: {
            type: Boolean,
            default: false
        },
    },
    methods: {
        doHeartBeat() {
            return new Promise((resolve, reject) => {
                let result = false;
                api.middle.heartBeat().then(res => {
                    if (res.data && res.data.code === 0) {
                        result = true;
                    } else {
                        console.warn('心跳异常! %s', new Date().fmt(), res)
                    }
                    resolve(result);
                }).catch((e) => {
                    window.e = e;
                    console.error('心跳失败! %s %s', new Date().fmt(), e);
                    resolve(result);
                })
            });
        },
        doNextTimeOut() {
            this.lastTimeOutId = setTimeout(() => {
                clearTimeout(this.lastTimeOutId);
                if (this.exit) {
                    return;
                }
                this.doHeartBeat().then(success => {
                    if (success) {
                        this.timeoutMs = appConfig.heartBeatFixedDelay * 1000;
                        this.lastCostTime = Date.now() - this.lastSuccessTime;
                        this.lastSuccessTime = Date.now();
                        console.log('[%s] 心跳正常! 间隔%s秒', new Date().fmt(), this.lastCostTime / 1000);
                    } else {
                        this.timeoutMs = this.timeoutMs + this.punishMs;
                        console.warn('心跳超时惩罚: %ss', this.timeoutMs / 1000);
                    }
                    this.doNextTimeOut();
                });
            }, this.timeoutMs)
        }
    },
    mounted() {
        console.log('HeartBeat mounted');
        this.doNextTimeOut();
    },
    unmounted() {
        console.log('HeartBeat unMounted, lastTimeOutId: %s', this.lastTimeOutId);
        clearTimeout(this.lastTimeOutId);
        this.exit = true;
        console.log('HeartBeat exit!')
    },
    data() {
        const {useSlots} = Vue;
        return {
            punishMs: appConfig.heartBeatPunish * 1000,
            lastTimeOutId: -1,
            timeoutMs: appConfig.heartBeatFixedDelay * 1000,
            lastSuccessTime: Date.now(),
            lastCostTime: -1,
            exit: false,
        }
    }
};